import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../store/authStore'
import { ElMessage } from 'element-plus'
import Auth from '../components/Auth.vue'
import Layout from '../components/Layout.vue'
import DeviceManager from '../components/DeviceManager.vue'
import MqttManager from '../components/MqttManager.vue'
import SystemManager from '../components/SystemManager.vue'
import DataCenter from '../components/DataCenter.vue'
import UserProfile from '../components/UserProfile.vue'
import NotFound from '../components/NotFound.vue'
import Dashboard from '../views/Dashboard.vue'
import DataItemManager from '../components/DataItemManager.vue'

const routes = [
  {
    path: '/',
    redirect: '/user/dashboard'
  },
  {
    path: '/user',
    redirect: '/user/dashboard'
  },
  {
    path: '/user/login',
    name: 'Login',
    component: Auth,
    meta: { requiresAuth: false, title: '登录' }
  },
  {
    path: '/user',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { requiresAuth: true, title: '大屏展示' }
      },
      {
        path: 'devices',
        name: 'Devices',
        component: DeviceManager,
        meta: { requiresAuth: true, title: '设备管理' }
      },
      {
        path: 'mqtt',
        name: 'MQTT',
        component: MqttManager,
        meta: { requiresAuth: true, title: 'MQTT管理' }
      },
      {
        path: 'data-center',
        name: 'DataCenter',
        component: DataCenter,
        meta: { requiresAuth: true, title: '数据中心' }
      },
      {
        path: 'system',
        name: 'System',
        component: SystemManager,
        meta: { requiresAuth: true, title: '系统管理' }
      },
      {
        path: 'data-items',
        name: 'DataItems',
        component: DataItemManager,
        meta: { requiresAuth: true, title: '数据项管理', requiresHighLevel: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: UserProfile,
        meta: { requiresAuth: true, title: '个人中心' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 设置页面标题
  const defaultTitle = '物联网数据平台'
  document.title = to.meta.title ? `${to.meta.title} - ${defaultTitle}` : defaultTitle
  
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 如果需要认证且未登录，重定向到登录页
    if (!authStore.isAuthenticated) {
      // 尝试从本地存储恢复登录状态
      const restored = authStore.checkAuth()
      if (!restored) {
        next({
          path: '/user/login',
          query: { redirect: to.fullPath }
        })
        return
      }
    }
    
    // 检查是否需要高级权限（LV1或LV2）
    if (to.matched.some(record => record.meta.requiresHighLevel)) {
      const userRole = authStore.getUserRole
      if (userRole !== 'LV1' && userRole !== 'LV2') {
        ElMessage.error('您没有权限访问此页面')
        next({ path: '/user/dashboard' })
        return
      }
    }
  }
  
  next()
})

export default router